package com.hanqian.kepler.web.controller.core;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.hanqian.kepler.common.bean.jqgrid.JqGridContent;
import com.hanqian.kepler.common.bean.jqgrid.JqGridFilter;
import com.hanqian.kepler.common.bean.jqgrid.JqGridPager;
import com.hanqian.kepler.common.bean.jqgrid.JqGridReturn;
import com.hanqian.kepler.common.bean.result.AjaxResult;
import com.hanqian.kepler.common.enums.DictEnum;
import com.hanqian.kepler.common.jpa.specification.Rule;
import com.hanqian.kepler.core.entity.primary.core.Target;
import com.hanqian.kepler.core.service.core.TargetService;
import com.hanqian.kepler.flow.entity.User;
import com.hanqian.kepler.flow.vo.ProcessLogVo;
import com.hanqian.kepler.security.annotation.CurrentUser;
import com.hanqian.kepler.web.annotation.RequestJsonParam;
import com.hanqian.kepler.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;

import java.math.BigDecimal;
import java.util.*;

/**
 * 指标卡片
 * ============================================================================
 * author : dzw
 * createDate:  2020/12/21 。
 * ============================================================================
 */
@Controller
@RequestMapping("target")
public class TargetController extends BaseController {
	
	@Autowired
	private TargetService targetService;

	/**
	 * list
	 */
	@GetMapping("list")
	@ResponseBody
	public JqGridReturn list(@CurrentUser User user, JqGridPager pager, @RequestJsonParam("filters") JqGridFilter filters,
	                         String ignoreIds, String formType){
		Pageable pageable = getJqGridPageable(pager);
		List<Rule> rules = getJqGridSearchWithFlow(filters);
		if(StrUtil.isNotBlank(ignoreIds)) Arrays.stream(StrUtil.split(ignoreIds, ",")).forEach(id -> rules.add(Rule.ne("id", id)));

		//选择父级指标场景，不能出现自己的子元素
		if(StrUtil.equals("parentSelect", formType) && StrUtil.isNotBlank(ignoreIds)) {
			List<String> sons = targetService.findAllSonList(ignoreIds);
			sons.forEach(id -> rules.add(Rule.ne("id", id)));
		}

		JqGridContent<Target> jqGridContent = targetService.getJqGridContentWithFlow(rules, pageable, user);

		List<Map<String, Object>> dataRows = new ArrayList<>();
		jqGridContent.getList().forEach(entity -> {
			Map<String, Object> map = new HashMap<>();
			map.put("id", entity.getId());
			map.put("name", StrUtil.emptyIfNull(entity.getName()));
			map.put("targetClassDict.name", entity.getTargetClassDict()!=null ? entity.getTargetClassDict().getName() : "");
			map.put("targetClassDict.id", entity.getTargetClassDict()!=null ? entity.getTargetClassDict().getId() : "");
			map.put("targetLevelStr", StrUtil.emptyIfNull(entity.getTargetLevelStr()));
			map.put("labelCount", StrUtil.split(entity.getTargetLabel(), "，").length);
			map.put("finishTime", DateUtil.format(entity.getFinishTime(), "yyyy-MM-dd HH:mm"));
			map.put("lastUpdateTime", DateUtil.format(entity.getLastUpdateTime(), "yyyy-MM-dd HH:mm"));
			map.put("pathCount", StrUtil.split(entity.getPath(), ",").length);
			dataRows.add(map);
		});
		return getJqGridReturn(dataRows, jqGridContent.getPage());
	}

	/**
	 * read页面
	 */
	@GetMapping("read")
	public String read(String keyId, Model model){
		Target target = targetService.get(keyId);
		model.addAttribute("target", target);

		model.addAttribute("targetClassDictList", getDictList(DictEnum.target_class)); //指标卡片

		if(target != null && StrUtil.isNotBlank(target.getParentTargetId())){
			Target parentTarget = targetService.get(target.getParentTargetId());
			model.addAttribute("parentTargetName", parentTarget!=null ? parentTarget.getName() : "");
		}
		return "main/core/target_read";
	}

	/**
	 * input页面
	 */
	@GetMapping("input")
	public String input(String keyId, Model model, String editType){
		Target target = targetService.get(keyId);
		model.addAttribute("target", target);
		model.addAttribute("editType", editType);

		model.addAttribute("targetClassDictList", getDictList(DictEnum.target_class)); //指标卡片
		if(target != null && StrUtil.isNotBlank(target.getParentTargetId())){
			Target parentTarget = targetService.get(target.getParentTargetId());
			model.addAttribute("parentTargetName", parentTarget!=null ? parentTarget.getName() : "");
		}
		return "main/core/target_input";
	}

	/**
	 * 赋值
	 */
	private Target setData(User user, String keyId, String name, String targetClassDictId, Integer level, String targetLabel){
		Target target = targetService.get(keyId);
		if(target == null){
			target = new Target();
			target.setCreator(user);
		}
		target.setName(name);
		target.setTargetClassDict(dictService.get(targetClassDictId));
		target.setTargetLabel(targetLabel);

		target.setLevel(level);
		if(ObjectUtil.equal(1, target.getLevel())) target.setTargetLevelStr("一级");
		if(ObjectUtil.equal(2, target.getLevel())) target.setTargetLevelStr("二级");
		if(ObjectUtil.equal(3, target.getLevel())) target.setTargetLevelStr("三级");

		return target;
	}

	/**
	 * 保存
	 */
	@PostMapping("save")
	@ResponseBody
	public AjaxResult save(@CurrentUser User user, ProcessLogVo processLogVo, String name, String targetClassDictId, Integer level, String targetLabel, String relatedTargetIds, String parentTargetId){
		Target target = setData(user,processLogVo.getKeyId(),name,targetClassDictId,level,targetLabel);

		if(StrUtil.isBlank(target.getId())){
			return targetService.draft(target);
		}else{
			target = targetService.save(target);
			if(StrUtil.isNotBlank(target.getId())){
				targetService.updateRelatedTarget(target, relatedTargetIds);
				targetService.updateParentTarget(target, parentTargetId);
			}
			return AjaxResult.success("保存成功");
		}
	}

	/**
	 * 修改标签
	 */
	@PostMapping("saveLabel")
	@ResponseBody
	public AjaxResult saveLabel(@CurrentUser User user, String keyId, String targetLabel){
		Target target = targetService.get(keyId);
		if(target != null){
			target.setTargetLabel(targetLabel);
			target = targetService.save(target);
			return AjaxResult.successWithId("保存成功", target.getId());
		}
		return AjaxResult.error();
	}

	/**
	 * 修改关联指标
	 */
	@PostMapping("saveRelated")
	@ResponseBody
	public AjaxResult saveRelated(@CurrentUser User user, String keyId, String relatedTargetIds){
		Target target = targetService.get(keyId);
		if(target != null){
			targetService.updateRelatedTarget(target, relatedTargetIds);
			return AjaxResult.successWithId("保存成功", target.getId());
		}
		return AjaxResult.error();
	}

	/**
	 * 提交
	 */
	@PostMapping("commit")
	@ResponseBody
	public AjaxResult commit(@CurrentUser User user, ProcessLogVo processLogVo, String name, String targetClassDictId, Integer level, String targetLabel, String relatedTargetIds, String parentTargetId){
		Target target = setData(user,processLogVo.getKeyId(),name,targetClassDictId,level,targetLabel);
		if(StrUtil.isBlank(target.getTargetNo())) target.setTargetNo(targetService.getNewTargetNo(new Date()));
		if(StrUtil.isBlank(target.getYear())) target.setYear(DateUtil.format(new Date(), "yyyy"));
		if(StrUtil.isBlank(target.getMonth())) target.setMonth(DateUtil.format(new Date(), "MM"));

		AjaxResult ajaxResult =  targetService.commit(target, processLogVo);
		if(1 == ajaxResult.getState()){
			target = targetService.get(ajaxResult.getId());
			targetService.updateRelatedTarget(target, relatedTargetIds);
			targetService.updateParentTarget(target, parentTargetId);
		}
		return ajaxResult;
	}

	/**
	 * 审批
	 */
	@PostMapping("approve")
	@ResponseBody
	public AjaxResult approve(@CurrentUser User user, ProcessLogVo processLogVo){
		Target target = targetService.get(processLogVo.getKeyId());
		return targetService.approve(target, processLogVo);
	}

	/**
	 * 退回
	 */
	@PostMapping("back")
	@ResponseBody
	public AjaxResult back(@CurrentUser User user, ProcessLogVo processLogVo){
		Target target = targetService.get(processLogVo.getKeyId());
		return targetService.back(target, processLogVo);
	}

	/**
	 * 否决
	 */
	@PostMapping("deny")
	@ResponseBody
	public AjaxResult deny(@CurrentUser User user, ProcessLogVo processLogVo){
		Target target = targetService.get(processLogVo.getKeyId());
		return targetService.deny(target, processLogVo);
	}

	/**
	 * 撤回
	 */
	@PostMapping("withdraw")
	@ResponseBody
	public AjaxResult withdraw(@CurrentUser User user, ProcessLogVo processLogVo){
		Target target = targetService.get(processLogVo.getKeyId());
		return targetService.withdraw(target, processLogVo);
	}
	
}
